﻿using IBll;
using IDal;
using Model;

namespace Bll
{
    public class HouseBll : IHouseBll
    {
        public HouseBll(IBaseDal<House> houseDal,IBaseDal<HouseType> typeDal)
        {
            HouseDal = houseDal;
            TypeDal = typeDal;
        }

        public IBaseDal<House> HouseDal { get; }
        public IBaseDal<HouseType> TypeDal { get; }

        public Task<int> AddAsync(House house)
        {
            return HouseDal.AddAsync(house);
        }

        public Task<int> DeleteAsync(int id)
        {
            var m = HouseDal.GetValues().FirstOrDefault(x => x.Id == id);
            m.IsDelete = true;
            return HouseDal.UpdateAsync(m);
        }

        public dynamic GetHouses(string? name, int? typeid, int size, int index)
        {
            var houses = HouseDal.GetValues().Where(x => x.IsDelete == false);
            var types = TypeDal.GetValues();
            var list = from a in houses
                       join b in types
                       on a.TypeId equals b.TypeId
                       select new
                       {
                           a.Id,
                           a.Name,
                           a.State,
                           a.Price,
                           a.Phone,
                           a.TypeId,
                           b.TypeName
                       };
            if (!string.IsNullOrEmpty(name))
            {
                list = list.Where(x=>x.Name.Equals(name));
            }
            if (typeid > 0)
            {
                list = list.Where(x=>x.TypeId == typeid);
            }
            int count = list.Count();
            var rows = list.OrderBy(x => x.Id).Skip((index - 1) * size).Take(size);
            return new
            {
                count,
                rows
            };
        }

        public Task<int> UpdateAsync(House house)
        {
            return HouseDal.UpdateAsync(house);
        }
    }
}
